import type { DataSource, DataSourceResponse } from "@/types/dataSource";
import type { ApiConfig, ApiResponse } from "@/types/api";
import { DataSourceStatus, DataSourceType } from "@/types/dataSource";
import { ApiMethod, ApiStatus, ApiType } from "@/types/api";
import {
  TableListResponse,
  ColumnInfo,
  TableDataQuery,
  TableDataResponse,
} from "@/types/dataSource";
import { MockMethod } from "vite-plugin-mock";
import dataSourceMocks from "./dataSourceMock";
import apiMocks from "./apiMock";
import { generateMockDataForSql } from "@/api/dataSource";

// Mock 数据源列表
const mockDataSources: DataSource[] = [
  {
    id: 1,
    name: "主数据库",
    type: DataSourceType.MySQL,
    host: "localhost",
    port: 3306,
    username: "root",
    password: "******",
    database: "main_db",
    status: DataSourceStatus.Connected,
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
  {
    id: 2,
    name: "Redis缓存",
    type: DataSourceType.Redis,
    host: "redis.example.com",
    port: 6379,
    username: "admin",
    password: "******",
    database: "0",
    status: DataSourceStatus.Connected,
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
];

// Mock API列表
const mockApis: ApiConfig[] = [
  {
    id: 1,
    name: "用户查询",
    path: "/api/users",
    method: ApiMethod.GET,
    type: ApiType.DataSource,
    status: ApiStatus.Enabled,
    description: "查询用户列表",
    dataSourceId: 1,
    config: {
      sql: "SELECT * FROM users WHERE status = :status",
      params: {
        status: { type: "number", defaultValue: 1 },
      },
      cache: {
        enabled: true,
        timeout: 60000,
      },
      page: {
        enabled: true,
        pageSize: 20,
      },
    },
    requestSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          userId: { type: "number" },
        },
        required: ["userId"],
      },
      null,
      2
    ),
    responseSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          id: { type: "number" },
          username: { type: "string" },
          email: { type: "string" },
        },
      },
      null,
      2
    ),
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
  {
    id: 2,
    name: "订单详情",
    path: "/api/orders/:id",
    method: ApiMethod.GET,
    type: ApiType.REST,
    status: ApiStatus.Enabled,
    description: "获取订单详情",
    config: {
      request: {
        method: "GET",
        tag: "order",
        version: "1.0",
        structure: {
          order: {
            id: "/id",
          },
          "order_items@": {
            "order_id@": "order/id",
          },
        },
      },
      query: {
        cache: true,
        type: "QUERY",
        fields: ["*"],
      },
      access: {
        needLogin: true,
        role: ["user", "admin"],
      },
    },
    requestSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          city: { type: "string" },
        },
        required: ["city"],
      },
      null,
      2
    ),
    responseSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          temperature: { type: "number" },
          humidity: { type: "number" },
          description: { type: "string" },
        },
      },
      null,
      2
    ),
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
];

// Mock 延迟函数
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// Mock API 响应
export const mockApi = {
  // 数据源相关接口
  async getDataSourceList(params: {
    keyword?: string;
    page: number;
    pageSize: number;
  }): Promise<DataSourceResponse> {
    await delay(500);
    let list = [...mockDataSources];

    if (params.keyword) {
      list = list.filter(
        (item) =>
          item.name.toLowerCase().includes(params.keyword!.toLowerCase()) ||
          item.host.toLowerCase().includes(params.keyword!.toLowerCase())
      );
    }

    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;

    return {
      list: list.slice(start, end),
      total: list.length,
    };
  },

  async createDataSource(data: Omit<DataSource, "id">): Promise<DataSource> {
    await delay(500);
    const newDataSource: DataSource = {
      ...data,
      id: Math.max(...mockDataSources.map((ds) => ds.id ?? 0)) + 1,
      status: DataSourceStatus.Connected,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    mockDataSources.push(newDataSource);
    return newDataSource;
  },

  async updateDataSource(
    id: number,
    data: Partial<DataSource>
  ): Promise<DataSource> {
    await delay(500);
    const index = mockDataSources.findIndex((ds) => ds.id === id);
    if (index === -1) {
      throw new Error("数据源不存在");
    }
    mockDataSources[index] = {
      ...mockDataSources[index],
      ...data,
      updatedAt: new Date().toISOString(),
    };
    return mockDataSources[index];
  },

  async deleteDataSource(id: number): Promise<void> {
    await delay(500);
    const index = mockDataSources.findIndex((ds) => ds.id === id);
    if (index === -1) {
      throw new Error("数据源不存在");
    }
    mockDataSources.splice(index, 1);
  },

  async testDataSourceConnection(
    id: number
  ): Promise<{ success: boolean; message: string }> {
    await delay(1000);
    const dataSource = mockDataSources.find((ds) => ds.id === id);
    if (!dataSource) {
      return { success: false, message: "数据源不存在" };
    }
    return { success: true, message: "连接成功" };
  },

  // API相关接口
  async getApiList(params: ApiQuery): Promise<ApiResponse> {
    await delay(500);
    let list = [...mockApis];

    if (params.keyword) {
      const keyword = params.keyword.toLowerCase();
      list = list.filter(
        (api) =>
          api.name.toLowerCase().includes(keyword) ||
          api.path.toLowerCase().includes(keyword)
      );
    }

    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    return {
      list: list.slice(start, end),
      total: list.length,
    };
  },

  async createApi(data: Omit<ApiConfig, "id">): Promise<ApiConfig> {
    await delay(500);
    const newApi: ApiConfig = {
      ...data,
      id: Math.max(...mockApis.map((api) => api.id ?? 0)) + 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    mockApis.push(newApi);
    return newApi;
  },

  async updateApi(id: number, data: Partial<ApiConfig>): Promise<ApiConfig> {
    await delay(500);
    const index = mockApis.findIndex((api) => api.id === id);
    if (index === -1) {
      throw new Error("API不存在");
    }
    mockApis[index] = {
      ...mockApis[index],
      ...data,
      updatedAt: new Date().toISOString(),
    };
    return mockApis[index];
  },

  async deleteApi(id: number): Promise<void> {
    await delay(500);
    const index = mockApis.findIndex((api) => api.id === id);
    if (index === -1) {
      throw new Error("API不存在");
    }
    mockApis.splice(index, 1);
  },

  async testApi(
    id: number
  ): Promise<{ success: boolean; message: string; data?: any }> {
    await delay(1000);
    const api = mockApis.find((api) => api.id === id);
    if (!api) {
      return { success: false, message: "API不存在" };
    }

    // 模拟测试结果
    if (api.type === ApiType.DataSource) {
      return {
        success: true,
        message: "SQL执行成功",
        data: {
          sql: (api.config as SqlConfig).sql,
          params: (api.config as SqlConfig).params,
        },
      };
    } else {
      return {
        success: true,
        message: "REST接口调用成功",
        data: {
          url: (api.config as RestConfig).url,
          method: (api.config as RestConfig).method,
        },
      };
    }
  },

  async getTableList(dataSourceId: number): Promise<TableListResponse> {
    await delay(500);
    return {
      tables: [
        { name: "users", comment: "用户表", type: "table" },
        { name: "orders", comment: "订单表", type: "table" },
        { name: "products", comment: "商品表", type: "table" },
      ],
      views: [
        { name: "order_details", comment: "订单详情视图", type: "view" },
        { name: "product_stats", comment: "商品统计视图", type: "view" },
      ],
    };
  },

  async getTableStructure(
    dataSourceId: number,
    tableName: string
  ): Promise<ColumnInfo[]> {
    await delay(500);
    return [
      {
        name: "id",
        type: "int",
        nullable: false,
        key: "PRI",
        comment: "主键ID",
      },
      {
        name: "name",
        type: "varchar(50)",
        nullable: false,
        comment: "名称",
      },
      {
        name: "status",
        type: "tinyint",
        nullable: false,
        default: "1",
        comment: "状态",
      },
      {
        name: "created_at",
        type: "datetime",
        nullable: true,
        comment: "创建时间",
      },
    ];
  },

  async getTableData(
    dataSourceId: number,
    tableName: string,
    query: TableDataQuery
  ): Promise<TableDataResponse> {
    await delay(500);
    const mockData = Array.from({ length: 100 }, (_, i) => ({
      id: i + 1,
      name: `测试数据 ${i + 1}`,
      status: Math.random() > 0.5 ? 1 : 0,
      created_at: new Date().toISOString(),
    }));

    const start = (query.page - 1) * query.pageSize;
    const end = start + query.pageSize;

    return {
      list: mockData.slice(start, end),
      total: mockData.length,
    };
  },

  async getDataSourceStructure(id: number): Promise<ApiResponse> {
    await delay(600); // 模拟网络延迟

    // 根据 ID 查找数据源
    const dataSource = mockDataSources.find((ds) => ds.id === id);

    if (!dataSource) {
      return {
        code: 404,
        success: false,
        message: "数据源不存在",
        data: null,
      };
    }

    // 根据数据源类型生成结构
    const structure = generateStructureByDataSourceType(dataSource.type);

    return {
      code: 0,
      success: true,
      message: "获取成功",
      data: structure,
    };
  },

  async executeQuery(id: number, sql: string): Promise<ApiResponse> {
    await delay(800); // 模拟网络延迟

    // 根据 ID 查找数据源
    const dataSource = mockDataSources.find((ds) => ds.id === id);

    if (!dataSource) {
      return {
        code: 404,
        success: false,
        message: "数据源不存在",
        data: null,
      };
    }

    try {
      // 确保数据源类型为小写字符串，与 generateMockDataForSql 函数期望的格式一致
      const dataSourceType = dataSource.type.toLowerCase();
      console.log(
        `执行查询 - 数据源ID: ${id}, 类型: ${dataSourceType}, SQL: ${sql}`
      );

      // 根据数据源类型和 SQL 生成模拟数据
      const data = generateMockDataForSql(dataSourceType, sql);

      // 获取列名
      let columns = [];
      if (data.length > 0) {
        columns = Object.keys(data[0]);
      }

      return {
        code: 0,
        success: true,
        message: "执行成功",
        data: {
          columns,
          data,
          sql,
          dataSourceType: dataSourceType, // 返回数据源类型，便于前端显示
        },
      };
    } catch (error) {
      console.error("执行查询失败:", error);
      return {
        code: 500,
        success: false,
        message: `执行失败: ${error.message || "未知错误"}`,
        data: null,
      };
    }
  },
};

// 模拟数据源列表
const dataSourceList = [
  {
    id: 1,
    name: "MySQL测试库",
    type: DataSourceType.MySQL,
    host: "localhost",
    port: 3306,
    database: "test_db",
    username: "root",
    password: "123456",
    status: DataSourceStatus.Connected,
    createdAt: "2023-06-01 10:00:00",
    updatedAt: "2023-06-01 10:00:00",
  },
  {
    id: 2,
    name: "PostgreSQL数据仓库",
    type: DataSourceType.PostgreSQL,
    host: "192.168.1.100",
    port: 5432,
    database: "data_warehouse",
    username: "postgres",
    password: "postgres",
    status: DataSourceStatus.Disconnected,
    createdAt: "2023-06-02 14:30:00",
    updatedAt: "2023-06-02 14:30:00",
  },
  {
    id: 3,
    name: "Oracle企业库",
    type: DataSourceType.Oracle,
    host: "oracle-server",
    port: 1521,
    database: "ORCL",
    username: "system",
    password: "manager",
    status: DataSourceStatus.Error,
    createdAt: "2023-06-03 09:15:00",
    updatedAt: "2023-06-03 09:15:00",
  },
];

// 添加一个函数，根据数据源类型生成不同的模拟表结构
function generateStructureByDataSourceType(dataSourceType: string): any[] {
  console.log(`生成数据源类型 ${dataSourceType} 的模拟结构`);

  // 基础结构，适用于所有数据库
  const baseStructure = [
    {
      type: "folder",
      label: "表",
      children: [],
    },
    {
      type: "folder",
      label: "视图",
      children: [],
    },
  ];

  const tables = baseStructure[0].children;
  const views = baseStructure[1].children;

  // 根据不同数据库类型生成不同的表结构
  switch (dataSourceType) {
    case "mysql": {
      // MySQL 特有表
      tables.push(
        {
          type: "table",
          label: "users",
          columns: ["id", "username", "email", "created_at"],
        },
        {
          type: "table",
          label: "orders",
          columns: ["id", "user_id", "amount", "status", "order_date"],
        },
        {
          type: "table",
          label: "products",
          columns: ["id", "name", "price", "stock", "category_id"],
        },
        {
          type: "table",
          label: "categories",
          columns: ["id", "name", "parent_id"],
        }
      );
      views.push(
        {
          type: "view",
          label: "active_users",
          columns: ["id", "username", "last_login"],
        },
        {
          type: "view",
          label: "order_summary",
          columns: ["order_id", "customer", "total", "items"],
        }
      );
      break;
    }
    case "postgresql": {
      // PostgreSQL 特有表
      tables.push(
        {
          type: "table",
          label: "accounts",
          columns: ["id", "name", "email", "created_on"],
        },
        {
          type: "table",
          label: "transactions",
          columns: ["id", "account_id", "amount", "transaction_date", "type"],
        },
        {
          type: "table",
          label: "items",
          columns: ["id", "name", "description", "price", "tags"],
        },
        {
          type: "table",
          label: "logs",
          columns: ["id", "level", "message", "context", "timestamp"],
        }
      );
      views.push(
        {
          type: "view",
          label: "monthly_report",
          columns: ["month", "revenue", "expenses", "profit"],
        },
        {
          type: "view",
          label: "user_activity",
          columns: ["user_id", "action", "resource", "timestamp"],
        }
      );
      break;
    }
    case "sqlserver": {
      // SQL Server 特有表
      tables.push(
        {
          type: "table",
          label: "Employees",
          columns: [
            "EmployeeID",
            "FirstName",
            "LastName",
            "Department",
            "HireDate",
          ],
        },
        {
          type: "table",
          label: "Customers",
          columns: [
            "CustomerID",
            "CompanyName",
            "ContactName",
            "Address",
            "City",
            "Country",
          ],
        },
        {
          type: "table",
          label: "Projects",
          columns: [
            "ProjectID",
            "Name",
            "StartDate",
            "EndDate",
            "Budget",
            "Status",
          ],
        },
        {
          type: "table",
          label: "Tasks",
          columns: [
            "TaskID",
            "ProjectID",
            "Description",
            "AssignedTo",
            "Priority",
            "Completed",
          ],
        }
      );
      views.push(
        {
          type: "view",
          label: "ProjectSummary",
          columns: [
            "ProjectID",
            "Name",
            "TaskCount",
            "CompletionRate",
            "Status",
          ],
        },
        {
          type: "view",
          label: "EmployeePerformance",
          columns: [
            "EmployeeID",
            "Name",
            "TasksCompleted",
            "AverageTime",
            "Rating",
          ],
        }
      );
      break;
    }
    case "oracle": {
      // Oracle 特有表
      tables.push(
        {
          type: "table",
          label: "EMPLOYEES",
          columns: [
            "EMPLOYEE_ID",
            "FIRST_NAME",
            "LAST_NAME",
            "DEPARTMENT_ID",
            "SALARY",
            "HIRE_DATE",
          ],
        },
        {
          type: "table",
          label: "DEPARTMENTS",
          columns: [
            "DEPARTMENT_ID",
            "DEPARTMENT_NAME",
            "MANAGER_ID",
            "LOCATION_ID",
          ],
        },
        {
          type: "table",
          label: "LOCATIONS",
          columns: [
            "LOCATION_ID",
            "STREET_ADDRESS",
            "CITY",
            "STATE_PROVINCE",
            "COUNTRY_ID",
          ],
        },
        {
          type: "table",
          label: "JOB_HISTORY",
          columns: [
            "EMPLOYEE_ID",
            "START_DATE",
            "END_DATE",
            "JOB_ID",
            "DEPARTMENT_ID",
          ],
        }
      );
      views.push(
        {
          type: "view",
          label: "EMP_DETAILS_VIEW",
          columns: [
            "EMPLOYEE_ID",
            "JOB_TITLE",
            "FIRST_NAME",
            "LAST_NAME",
            "DEPARTMENT_NAME",
            "CITY",
          ],
        },
        {
          type: "view",
          label: "DEPARTMENT_STATS",
          columns: [
            "DEPARTMENT_ID",
            "DEPARTMENT_NAME",
            "EMPLOYEE_COUNT",
            "AVG_SALARY",
            "MIN_SALARY",
            "MAX_SALARY",
          ],
        }
      );
      break;
    }
    default: {
      // 默认通用表
      tables.push(
        { type: "table", label: "users", columns: ["id", "name", "email"] },
        { type: "table", label: "items", columns: ["id", "name", "price"] }
      );
      views.push({
        type: "view",
        label: "active_users",
        columns: ["id", "name", "last_login"],
      });
    }
  }

  return baseStructure;
}

export default [...dataSourceMocks, ...apiMocks] as MockMethod[];
